package com.taotao.content.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EasyUIDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.JsonUtils;
import com.taotao.content.redis.JedisClient;
import com.taotao.content.service.ContentService;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
@Service
public class ContentServiceImpl implements ContentService {
	private static final Logger LOGGER = LoggerFactory.getLogger(ContentServiceImpl.class);
	
	@Autowired
	private TbContentMapper contentMapper;
	
	@Autowired
	private JedisClient JedisClient;
	
	@Value("${CONTENT_KEY}")
	private String CONTENT_KEY;
	
	@Override
	public TaotaoResult saveContent(TbContent content) {
		content.setCreated(new Date());
		content.setUpdated(content.getCreated());
		contentMapper.insertSelective(content);
		return TaotaoResult.ok();
	}

	@Override
	public EasyUIDataGridResult getContentListByCid(Long categoryId, Integer page, Integer rows) {
		EasyUIDataGridResult result  = new EasyUIDataGridResult();
		TbContentExample contentExample = new TbContentExample();
		contentExample.createCriteria().andCategoryIdEqualTo(categoryId);
		PageHelper.startPage(page, rows);
//		List<TbContent> list = contentMapper.selectByExampleWithBLOBs(contentExample);
		List<TbContent> list = contentMapper.selectByExample(contentExample);
		LOGGER.info("#####################"+list);
		PageInfo<TbContent> info = new PageInfo<>(list);
		result.setTotal((int)info.getTotal());
		result.setRows(info.getList());
		return result;
	}

	@Override
	public List<TbContent> getContentByCid(Long categoryId) {
		try {
			//从redis中获取
			String json = JedisClient.hget(CONTENT_KEY, categoryId+"");
			if (StringUtils.isNotBlank(json)) {
				LOGGER.info("redis中存在缓存数据");
				return JsonUtils.jsonToList(json, TbContent.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		TbContentExample example = new TbContentExample();
		example.createCriteria().andCategoryIdEqualTo(categoryId);
		List<TbContent> result = contentMapper.selectByExample(example);
		try {
			LOGGER.info("redis中不存在缓存数据");
			JedisClient.hset(CONTENT_KEY, categoryId+"", JsonUtils.objectToJson(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
